package com.stp.config.sign;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Signature {

    private static final String HmacSHA1 = "HmacSHA1";

    /**
     * 获取签名
     * @param secretKey 密钥
     * @param data  需要签名的数据
     * @return  签名
     */
    public static String signWithHmacSha1(String secretKey, String data) {

        try {
            SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), HmacSHA1);
            Mac mac = Mac.getInstance(HmacSHA1);
            mac.init(signingKey);
            return Base64.getEncoder().encodeToString(mac.doFinal(data.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 验证签名
     * @param secretKey 密钥
     * @param data  需要签名的数据
     * @param hmac  已经签名的数据
     * @return  true:签名一致
     */
    public static boolean verify(String secretKey, String data, String hmac) {
        String calculatedHmac = signWithHmacSha1(secretKey, data);
        return calculatedHmac.equals(hmac);
    }
}
